const fs = require('fs');
const path = require('path');


const readFiletoLines = (filename) => {
  let filepath = './text/' + filename
  console.log("load ", filepath);

  if (!fs.existsSync(filepath)) {
     filepath = './text/lines.txt'
  }
  const lines_str = fs.readFileSync(filepath,"utf8")
  let lines = lines_str.split(/\s/)
  lines = lines.filter((one) => {
    return one.length > 0
  })
  return lines;
};

const chapter_lines_map = {}


for (let i = 1; i <= 4; ++i) {
  chapter_lines_map[i] = readFiletoLines("Chapter0" + i + ".txt")
}

console.log(chapter_lines_map);

let now_chapter = 1

const get_random_lines = () => {
  const lines = chapter_lines_map[now_chapter]
  return lines[Math.floor(Math.random() * lines.length)]
}

const changeChapter = (new_chapter) => {
  new_chapter = parseInt(new_chapter)
  new_chapter = new_chapter.clamp(1,4)
  console.log("change chapter to",new_chapter);
  now_chapter = new_chapter
  return now_chapter
}

module.exports = {
  changeChapter,
  get_random_lines,
}


